package com.beyond.market.orders.service.impl;
import com.beyond.market.cart.dao.CartMapper;
import com.beyond.market.cart.domain.Cart;
import com.beyond.market.commodity.dao.CommodityMapper;
import com.beyond.market.orders.domain.OrderDetails;
import com.beyond.market.orders.domain.Orders;
import com.beyond.market.orders.service.CreateOrderService;
import com.beyond.market.orders.service.OrderDetailsService;
import com.beyond.market.orders.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Service
public class CreateOrderServiceImpl implements CreateOrderService {
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailsService orderDetailsService;
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public Integer createOrder(List<Integer> list) throws SQLException {
        List<Cart> cartList = new ArrayList<>();
        for (int id:
             list) {
            Cart c = cartMapper.getByPrimaryKey(id);
            cartList.add(c);
        }
        Double totalPrice = 0.0;
        for (Cart cart:
             cartList) {
            commodityMapper.update(cart.getCommodityId(),Integer.parseInt(cart.getBuyNum()));
            Double commodityPrice = commodityMapper.getPriceById(cart.getCommodityId());
            totalPrice += Integer.parseInt(cart.getBuyNum())*commodityPrice;
        }
        Orders orders = new Orders();
        orders.setUserId(cartList.get(0).getUserId());
        orders.setOrderPrice(totalPrice);
        Integer save = ordersService.save(orders);
        Integer orderId = ordersService.getLastId();

        for (Cart cart:
             cartList) {
            OrderDetails orderDetails = new OrderDetails();
            orderDetails.setCartId(cart.getCartId());
            orderDetails.setOrderId(orderId);
            orderDetailsService.save(orderDetails);
        }
        for (Cart cart : cartList) {
            cartMapper.remove(cart.getCartId());
        }
        return save;
    }
}
